package com.junhong.forum.common;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;

import com.junhong.auth.entity.User;
import com.junhong.auth.service.UserEjb;
import com.junhong.util.EncryptionUtil;

@LocalBean
@Stateless
public class SendEmailService {

	@Resource(name = "mail/gmailaccount")
	private Session	mailSession;

	@Inject
	private Logger	logger;

	@Inject
	private UserEjb	userEjb;

	public void sendResetPassword(String userId, String emailAddress) {

		String tempPwd = generateRandomPassword();

		try {
			// update user password to the temppwd
			User user = userEjb.getUserByUserId(userId);
			user.setPassword(EncryptionUtil.md5(tempPwd));
			userEjb.updateUser(user);
			MimeMessage message = new MimeMessage(mailSession);
			Address toAddress = new InternetAddress(emailAddress);
			message.setRecipient(RecipientType.TO, toAddress);
			// message.setSubject(subject);
			// message.setText(message text);
			populateMailSubjectContent(message, tempPwd);
			message.saveChanges();
			Transport tr = mailSession.getTransport();
			String serverPassword = mailSession.getProperty("mail.password");
			tr.connect(null, serverPassword);
			tr.sendMessage(message, message.getAllRecipients());
			tr.close();

		} catch (MessagingException e) {
			e.printStackTrace();
			throw new RuntimeException("Not able to send emails " + e.getMessage());
		} finally {

		}
	}

	private void populateMailSubjectContent(MimeMessage message, String tempPwd) {

		String emailSubject = Messages.getString(null, Constants.USER_RESET_PWD_EMAIL_SUBJECT, null);

		String[] parms = { tempPwd };
		String emailContent = Messages.getString(null, Constants.USER_RESET_PWD_EMAIL_CONTENT_TEMPLATE, parms);

		try {
			message.setSubject(emailSubject);
			message.setText(emailContent);
		} catch (MessagingException e) {
			e.printStackTrace();
			logger.error("Not able to set Email Message due to {1}", e.getMessage());

		}

	}

	private String generateRandomPassword() {

		return RandomStringUtils.randomAlphanumeric(10);
	}
}
